#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
快速分析工具 - 用于查看特定字段的数据
"""

import os
import sys
import numpy as np
import matplotlib.pyplot as plt
from orangebox import Parser

# 设置中文字体
plt.rcParams['font.sans-serif'] = ['SimHei', 'Microsoft YaHei', 'DejaVu Sans']
plt.rcParams['axes.unicode_minus'] = False

def analyze_single_file(log_file, fields_to_plot=None):
    """分析单个日志文件
    
    Args:
        log_file: 日志文件路径
        fields_to_plot: 要绘制的字段列表，如果为None则显示所有可用字段
    """
    if not os.path.exists(log_file):
        print(f"文件不存在: {log_file}")
        return
    
    print(f"\n分析文件: {os.path.basename(log_file)}")
    print("="*50)
    
    # 加载日志
    try:
        parser = Parser.load(log_file)
        print(f"日志数量: {parser.reader.log_count}")
        print(f"字段数量: {len(parser.field_names)}")
    except Exception as e:
        print(f"加载失败: {e}")
        return
    
    # 显示所有可用字段
    print("\n可用字段:")
    for i, field in enumerate(parser.field_names, 1):
        print(f"{i:2d}. {field}")
    
    if fields_to_plot is None:
        # 交互式选择字段
        print("\n请输入要绘制的字段编号 (用逗号分隔，如: 1,2,3):")
        try:
            indices = input().strip().split(',')
            indices = [int(i.strip()) - 1 for i in indices if i.strip().isdigit()]
            fields_to_plot = [parser.field_names[i] for i in indices if 0 <= i < len(parser.field_names)]
        except:
            print("输入无效，使用默认字段")
            fields_to_plot = ['time', 'setpoint[0]', 'gyroADC[0]', 'axisP[0]']
    
    if not fields_to_plot:
        print("没有选择有效字段")
        return
    
    print(f"\n绘制字段: {', '.join(fields_to_plot)}")
    
    # 提取数据
    data = {field: [] for field in fields_to_plot}
    frame_count = 0
    
    try:
        for frame in parser.frames():
            frame_count += 1
            for field in fields_to_plot:
                if field in parser.field_names:
                    idx = parser.field_names.index(field)
                    if idx < len(frame.data):
                        data[field].append(frame.data[idx])
                    else:
                        data[field].append(0)
                else:
                    data[field].append(0)
        
        print(f"提取了 {frame_count} 帧数据")
        
        # 转换为numpy数组
        for field in data:
            data[field] = np.array(data[field])
        
        # 绘制图表
        plot_fields(data, os.path.basename(log_file))
        
    except Exception as e:
        print(f"数据提取失败: {e}")
        import traceback
        traceback.print_exc()

def plot_fields(data, filename):
    """绘制字段数据"""
    fields = list(data.keys())
    n_fields = len(fields)
    
    if n_fields == 0:
        print("没有数据可绘制")
        return
    
    # 确定子图布局
    if n_fields == 1:
        rows, cols = 1, 1
    elif n_fields <= 2:
        rows, cols = 1, 2
    elif n_fields <= 4:
        rows, cols = 2, 2
    elif n_fields <= 6:
        rows, cols = 2, 3
    else:
        rows, cols = 3, 3
    
    fig, axes = plt.subplots(rows, cols, figsize=(15, 10))
    fig.suptitle(f'字段数据分析 - {filename}', fontsize=16, fontweight='bold')
    
    if rows == 1 and cols == 1:
        axes = [axes]
    elif rows == 1 or cols == 1:
        axes = axes.flatten()
    else:
        axes = axes.flatten()
    
    # 创建时间轴
    time_field = None
    for field in ['time', 'loopIteration']:
        if field in data and len(data[field]) > 0:
            time_field = field
            break
    
    if time_field:
        time_data = data[time_field]
        time_label = "时间 (μs)" if time_field == 'time' else "循环迭代"
    else:
        time_data = np.arange(len(next(iter(data.values()))))
        time_label = "数据点索引"
    
    # 绘制每个字段
    for i, field in enumerate(fields[:len(axes)]):
        ax = axes[i]
        
        if field == time_field:
            continue  # 跳过时间字段本身
        
        try:
            ax.plot(time_data, data[field], linewidth=1, alpha=0.8, label=field)
            ax.set_title(field)
            ax.set_xlabel(time_label)
            ax.set_ylabel('值')
            ax.grid(True, alpha=0.3)
            ax.legend()
        except Exception as e:
            ax.text(0.5, 0.5, f'绘制失败\n{str(e)}', 
                   transform=ax.transAxes, ha='center', va='center')
            ax.set_title(f'{field} (错误)')
    
    # 隐藏多余的子图
    for i in range(len(fields), len(axes)):
        axes[i].set_visible(False)
    
    plt.tight_layout()
    
    # 保存图表
    output_file = f"quick_analysis_{filename}.png"
    plt.savefig(output_file, dpi=300, bbox_inches='tight')
    print(f"图表已保存: {output_file}")
    
    plt.show()

def main():
    """主函数"""
    print("Betaflight 黑盒日志快速分析工具")
    print("="*40)
    
    # 可用的日志文件
    log_files = [
        "d:/Git/FlightRecord/SFPV_85/btfl_001.bbl",
        "d:/Git/FlightRecord/SFPV_85/btfl_002.bbl",
        "d:/Git/FlightRecord/SFPV_85/btfl_all.bbl"
    ]
    
    # 显示可用文件
    print("\n可用的日志文件:")
    available_files = []
    for i, file in enumerate(log_files, 1):
        if os.path.exists(file):
            size_mb = os.path.getsize(file) / (1024*1024)
            print(f"{i}. {os.path.basename(file)} ({size_mb:.1f} MB)")
            available_files.append(file)
        else:
            print(f"{i}. {os.path.basename(file)} (不存在)")
    
    if not available_files:
        print("没有找到可用的日志文件")
        return
    
    # 选择文件
    print("\n请选择要分析的文件编号:")
    try:
        choice = int(input().strip()) - 1
        if 0 <= choice < len(available_files):
            selected_file = available_files[choice]
        else:
            print("选择无效，使用第一个文件")
            selected_file = available_files[0]
    except:
        print("输入无效，使用第一个文件")
        selected_file = available_files[0]
    
    # 分析选定的文件
    analyze_single_file(selected_file)

if __name__ == "__main__":
    main()